package service

import (
	"EnjoyWorking/model"
	"EnjoyWorking/utils"
	"EnjoyWorking/utils/storage"
	"errors"
)

type Job struct {}

func (service *Job) Insert(job *model.Job) error {
	//检验部门是否存在
	var total int64
	if err := storage.MySqlDb().Model(&model.Department{}).Where("id = ?", job.DepartmentId).Count(&total).Error; err != nil {
		return err
	}

	if total == 0 {
		return errors.New(utils.CODE_DEPARTMENT_NOT_EXIST.String())
	}

	//检验岗位名称是否存在
	if err := storage.MySqlDb().Model(&model.Job{}).Where("name = ?", job.Name).Count(&total).Error; err != nil {
		return err
	}

	if total != 0 {
		return errors.New(utils.CODE_JOB_NAME_DUPLICATE.String())
	}

	return storage.MySqlDb().Create(job).Error
}

func (service *Job) FindByDepartmentId(departmentId uint) (int64, []*model.Job, error) {
	var (
		err    error
		total  int64
		result = make([]*model.Job, 0)
	)

	if err = storage.MySqlDb().Model(&model.Job{}).Where("department_id = ?", departmentId).Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().Model(&model.Job{}).Where("department_id = ?", departmentId).Preload("Department").Find(&result).Error; err != nil {
		goto ERR
	}

	return total, result, nil
ERR:
	return 0, nil, err
}

func (service *Job) FindOne(cond *model.Job) (*model.Job, error) {
	var (
		err   error
		result = model.Job{}
	)

	if err = storage.MySqlDb().Where(cond).First(&result).Error; err != nil {
		return nil, err
	}

	if err = storage.MySqlDb().Model(&result).Related(&result.Department).First(&result).Error; err != nil {
		return nil, err
	}

	return &result, nil
}

func (service *Job) FindList() (int64, []*model.Job, error) {
	var (
		err    error
		total  int64
		result = make([]*model.Job, 0)
	)

	if err = storage.MySqlDb().Model(&model.Job{}).Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().Model(&model.Job{}).Preload("Department").Find(&result).Error; err != nil {
		goto ERR
	}

	return total, result, nil
ERR:
	return 0, nil, err
}
